package com.liang.response.domain;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 常见的指数
 *
 * @author liangyehao
 * @date 2021/04/29
 */
@Data
public class CommonIndex {
    @ExcelProperty("会话量")
    private Integer sessionAmount;
    @ExcelProperty("23秒响应量")
    private Integer responseAmount;
    @ExcelProperty("23秒响应率")
    private BigDecimal responseRate;
    @ExcelProperty("二次分配客户量")
    private Integer secondaryDistributionCustomers;
    @ExcelProperty("会话比")
    private BigDecimal proportionOfSession;

    private List<Map<String, Field>> fieldMaps = new ArrayList<>();

    public CommonIndex(){
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation!=null) {
                String key = annotation.value()[0];
                Map<String, Field> map = new HashMap<>();
                map.put(key,field);
                this.fieldMaps.add(map);
            }
        }
    }

    public static CommonIndex build(List<Detail> details){

        CommonIndex commonIndex = new CommonIndex();

        List<Detail> in23List = details.stream().filter(detail -> detail.getResponseTime() <= 23).collect(Collectors.toList());
        int sessionAmount = details.size();
        int responseAmount = in23List.size();
        int secondaryDistributionCustomers = details.size() - in23List.size();
        BigDecimal responseRate = BigDecimal.valueOf(sessionAmount==0?0:(double) responseAmount / sessionAmount);

        // 会话比
        int agentSendSum = details.stream().mapToInt(Detail::getAgentSend).sum();
        int userSendSum = details.stream().mapToInt(Detail::getUserSend).sum();
        BigDecimal proportionOfSession = BigDecimal.valueOf(userSendSum==0?0:(double) agentSendSum / userSendSum);

        commonIndex.setSessionAmount(sessionAmount);
        commonIndex.setResponseAmount(responseAmount);
        commonIndex.setResponseRate(responseRate);
        commonIndex.setSecondaryDistributionCustomers(secondaryDistributionCustomers);
        commonIndex.setProportionOfSession(proportionOfSession);

        return commonIndex;
    }
}
